package com.liy.supercloud.ssoserver.runner;

import com.liy.framework.common.jwt.RsaKeyHelper;
import com.liy.framework.common.redis.utils.RedisUtils;
import com.liy.framework.common.token.Base64Utils;
import com.liy.framework.common.utils.Tools;
import com.liy.supercloud.ssoserver.config.AuthKeyConfig;
import java.util.Base64;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AuthInitializationRunner implements CommandLineRunner {

    private static Logger log = LoggerFactory.getLogger(AuthInitializationRunner.class);
    private static final String REDIS_USER_SECRET = "CAUTH:USER:SECRET";
    private static final String REDIS_USER_PRI_KEY = "CAUTH:USER:PRI";
    private static final String REDIS_USER_PUB_KEY = "CAUTH:USER:PUB";

    @Autowired
    private AuthKeyConfig keyConfig;

    @Autowired
    private RedisUtils redisUtils;

    public AuthInitializationRunner() {
    }

    public void run(String... args) throws Exception {
        String secret = (String)this.redisUtils.get("CAUTH:USER:SECRET");
        String pri = (String)this.redisUtils.get("CAUTH:USER:PRI");
        String pub = (String)this.redisUtils.get("CAUTH:USER:PUB");
        if (!Tools.StringIsNullOrSpace(pri) && !Tools.StringIsNullOrSpace(pub) && !Tools.StringIsNullOrSpace(secret) && this.keyConfig.getUserSecret().equals(new String(Base64.getDecoder().decode(secret), "UTF-8"))) {
            this.keyConfig.setUserPriKey(Base64Utils.decode(pri));
            this.keyConfig.setUserPubKey(Base64Utils.decode(pub));
            log.info("Authentication key old initialization successfully.");
        } else {
            Map<String, byte[]> keyMap = RsaKeyHelper.generateKey(this.keyConfig.getUserSecret());
            this.keyConfig.setUserPriKey((byte[])keyMap.get("pri"));
            this.keyConfig.setUserPubKey((byte[])keyMap.get("pub"));
            this.redisUtils.set("CAUTH:USER:SECRET", Base64.getEncoder().encodeToString(this.keyConfig.getUserSecret().getBytes("UTF-8")));
            this.redisUtils.set("CAUTH:USER:PRI", Base64Utils.encode((byte[])keyMap.get("pri")));
            this.redisUtils.set("CAUTH:USER:PUB", Base64Utils.encode((byte[])keyMap.get("pub")));
            log.info("Authentication key new initialization successfully.");
        }

    }
}
